<template>
  <div class="model-container">
    <div ref="threeContainer" class="three-container"></div>
  </div>
</template>
 
<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { initThreeScene, disposeScene } from '@/utils/palletUtils/threeConfig'
import { createWoodMaterial } from '@/utils/palletUtils/materialUtils'
import { createTwoWayPallet } from '@/utils/palletUtils/twoSidePallet'
import { createFourWayPallet } from '@/utils/palletUtils/fourSidePallet'
 
const props = defineProps({
  activeTab: {
    type: String,
    required: true,
    validator: value => ['two', 'four'].includes(value)
  },
  palletParams: {
    type: Object,
    required: true 
  }
})
 
const threeContainer = ref(null)
let scene = null 
 
// 带错误处理的更新函数 
const updatePallet = async () => {
  if (!scene) {
    console.warn('Three.js 场景未初始化')
    return 
  }
 
  try {
    const material = createWoodMaterial(0x8b4513)
    scene.clearPallet() 
 
    // 根据活动标签选择创建函数 
    const creator = props.activeTab  === 'two' 
      ? createTwoWayPallet 
      : createFourWayPallet 
    
    await creator(scene, material, props.palletParams) 
  } catch (error) {
    console.error(' 更新托盘模型失败:', error)
    // 可以在这里添加用户提示 
  }
}
 
// 初始化Three.js 场景 
onMounted(async () => {
  try {
    scene = initThreeScene(threeContainer.value) 
    await updatePallet()
  } catch (error) {
    console.error(' 初始化3D场景失败:', error)
  }
})
 
// 清理资源 
onUnmounted(() => {
  if (scene) {
    try {
      disposeScene(scene)
    } catch (error) {
      console.error(' 清理3D场景失败:', error)
    }
  }
})
 
// 监听参数变化 
watch(() => props.palletParams,  updatePallet, { 
  deep: true,
  flush: 'post' // 确保DOM更新后执行 
})
 
// 监听标签切换 
watch(() => props.activeTab,  async (newVal, oldVal) => {
  if (newVal !== oldVal) {
    await updatePallet()
  }
})
 
// 暴露方法给父组件 
defineExpose({ 
  updatePallet,
  getScene: () => scene 
})




</script>
 
<style scoped>
.model-container {
  flex: 1;
  position: relative;
  background-color: #f0f0f0;
  min-height: 400px; /* 确保最小高度 */
}
 
.three-container {
  position: absolute;
  width: 100%;
  height: 100%;
  touch-action: none; /* 防止移动端触摸冲突 */
}
 
/* 响应式调整 */
@media (max-width: 768px) {
  .model-container {
    height: 50vh;
  }
}
</style>